package com.af.security.mgt.account.register.token;

import com.af.security.mgt.user.User;
import com.af.security.property.SecurityProperties;
import com.af.service.AfMailService;
import com.af.system.exception.AfMailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @author : zhenyun.su
 * @comment :
 * @since : 2020/3/28
 */

@Service
public class UserRegisterTokenService {
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private UserRegisterTokenRepository userRegisterTokenRepository;
    @Autowired
    private AfMailService mailService;

    public UserRegisterToken createToken(Long userId) {
        UserRegisterToken confirmToken = new UserRegisterToken(UUID.randomUUID().toString(), userId);
        confirmToken.calculateExpiryDate(securityProperties.getTokenExpired());
        return userRegisterTokenRepository.save(confirmToken);
    }

    public UserRegisterToken resetToken(String existingToken) {
        UserRegisterToken confirmToken = this.findByToken(existingToken);
        confirmToken.setToken(UUID.randomUUID().toString());
        confirmToken.calculateExpiryDate(securityProperties.getTokenExpired());
        return userRegisterTokenRepository.save(confirmToken);
    }

    public UserRegisterToken findByToken(String token) {
        return userRegisterTokenRepository.getOne(token);
    }

    public void tokenDisable(UserRegisterToken token) {
        if (token != null) {
            token.setEnabled(false);
            userRegisterTokenRepository.save(token);
        }
    }

    /**
     * @return :
     * @comment : 生成注册token，并发送邮件
     * 必须将数据操作和发送邮件放在一个事务中执行，保证一致性
     * @params :
     */
    @Transactional(rollbackFor = Exception.class)
    public String sendTokenMail(User user, String subject, String text) throws AfMailException {
        UserRegisterToken token = createToken(user.getId());
        mailService.sendTextMail(user.getEmail(), subject, text + token.getToken());
        return token.getToken();
    }

    /**
     * @comment : 重新生成注册token并发送邮件,根据原来token
     */
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void resendTokenMail(User user, String existingToken, String subject, String text) throws AfMailException {
        UserRegisterToken token = resetToken(existingToken);
        mailService.sendTextMail(user.getEmail(), subject, text + token.getToken());
    }

}
